const { adminAccount }  = require('../config/config'),
      { createAdminAccount, login } = require('../services/Admin'),
      { makeCrypto, trimSpace, returnInfo } = require('../libs/utils'),
      { LOGIN } = require('../config/error_config');

class Admin {
   async addAdminAccount (ctx, next) {

       //用户密码加密
       adminAccount.password = makeCrypto(adminAccount.password);

       const result = await createAdminAccount(adminAccount);

       if (result) {
           console.log(0);
       } else {
           console.log(1);
       }
   }

   //登录验证检查
   async loginCheck (ctx, next) {
       //只要前端请求数据时携带了cookie,服务器就会自动去匹配是否存在,ctx.session.userInfo就能找到相对应的cookie是否存在session中
       //不需要我们去做什么,服务器自动去做的
       if (ctx.session && ctx.session.userInfo) {//则是登录状态
        
           ctx.body = returnInfo(LOGIN.LOGIN_STATUS);
           return;
       }
       
       //非登录状态
       ctx.body = returnInfo(LOGIN.NOT_LOGIN_STATUS);
   }

   //登录逻辑
   async loginAction (ctx, next) {
       const { username, password } = ctx.request.body;

       if (!username || !password) {
            ctx.body = returnInfo(LOGIN.INVALID_OPERATION);
            return;
        }

        if (trimSpace(username).length <= 3) {
            ctx.body = returnInfo(LOGIN.INVALID_USERNAME_LENGTH);
            return;
        }
    
        if (trimSpace(password).length <= 3) {
            ctx.body = returnInfo(LOGIN.INVALID_PASSWORD_LENGTH);
            return;
        }
    
        const userInfo = {
            username: trimSpace(username),
            password: makeCrypto(trimSpace(password))
        };

        const result = await login(userInfo);

        if (result === 10003) {//用户不存在
          ctx.body = returnInfo(LOGIN.USERNAME_NOT_EXIST);
          return;
        }
    
        if (result === 10004) {//密码错误
          ctx.body = returnInfo(LOGIN.PASSWORD_ERROR);
          return;
        }

        //如果不存在相对应的session,则设置result存储到session中
        if (!ctx.session.userInfo) {
            ctx.session.userInfo = result;
        }

       ctx.body = returnInfo(LOGIN.SUCCESS, ctx.session.userInfo);//登陆成功,返回数据
   }

   async logoutAction (ctx, next) {
       delete ctx.session.userInfo;
       ctx.body = returnInfo(LOGIN.LOGOUT_SUCCESS);
   }
}

module.exports = new Admin();